<?php

use GatewayWorker\Lib\DbConnection;

use Illuminate\Database\Capsule\Manager as Capsule;

class DB
{
    protected static $instance = null;

    protected static $config = [];

    private static function initConfig()
    {
        static::$config = [
            'driver' => config('DB_CONNECTION'),
            'host' => config('DB_HOST'),
            'username' => config('DB_USERNAME'),
            'password' => config('DB_PASSWORD'),
            'database' => config('DB_DATABASE'),
            'charset' => 'utf8',
            'port'  => config('DB_PORT'),
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ];
    }

    public static function initEloquent()
    {
        static::initConfig();

        $capsule = new Capsule;

        $capsule->addConnection(static::$config);

        $capsule->bootEloquent();
    }

    /**
     * @return DbConnection
     */
    public static function instance()
    {
        if (!is_null(static::$instance)) {
            return static::$instance;
        }

        $config = static::$config;
        static::$instance = new DbConnection($config['host'], $config['port'],
            $config['username'], $config['password'], $config['database'], $config['charset']);

        return static::$instance;
    }


    /**
     * 关闭数据库实例
     *
     * @param string $config_name
     */
    public static function close($config_name)
    {
        if (isset(self::$instance[$config_name])) {
            self::$instance[$config_name]->closeConnection();
            self::$instance[$config_name] = null;
        }
    }

    /**
     * 关闭所有数据库实例
     */
    public static function closeAll()
    {
        foreach (self::$instance as $connection) {
            $connection->closeConnection();
        }
        self::$instance = array();
    }
}